﻿
using Microsoft.Extensions.Options;
using System.Net.Http;
using System.Reflection.Metadata;
using XL.Crawler.Core;
using XL.Crawler.Core.Crawlers;
using XL.Crawler.Core.Crawlers.CrawlerEventArgs;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace XL.Crawler.Service
{
    /// <summary>
    /// 文章爬虫
    /// </summary>
    public class ArticleCrawler : CrawlerBase, ICrawler
    {
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="serviceProvider"></param>
        public ArticleCrawler(IServiceProvider serviceProvider) : base(serviceProvider)
        {

        }
        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        public override async Task StartAsync()
        {

            CrawlerParameter parameter = new CrawlerParameter()
            {
                Headers = { },
                HttpMethod = "get",
                Parameters = { },
                Proxy = null,
                Url = CrawlerOptions.Url,
            };
            try
            {
                OnStart(this, new StartEventArgs()
                {
                    Url = parameter.Url
                });

                var httpClient = HttpClientFactory.CreateClient();
                HttpResponseMessage? httpResponseMessage = await httpClient.GetAsync(parameter.Url);
                httpResponseMessage = httpResponseMessage.EnsureSuccessStatusCode();
                if (httpResponseMessage.IsSuccessStatusCode)
                {

                    string data = await httpResponseMessage.Content.ReadAsStringAsync();
                    OnCompleted(this, new CompletedEventArgs()
                    {
                        Data = data
                    });
                }
            }
            catch (Exception ex)
            {
                OnException(this, new ExceptionEventArgs()
                {
                    Exception = ex,
                    Message = ex.Message
                });
            }
        }
    }
}
